#!/bin/bash
#==============================================================#
# File      :   copy-progress
# Desc      :   Print logical replication progress by table size
# Time      :   {{ '%Y-%m-%d %H:%M' |strftime }}
# Path      :   {{ dir_path }}/copy-progress
# Deps      :   bash
# License   :   AGPLv3 @ https://pigsty.io/docs/about/license
# Copyright :   2018-2025  Ruohang Feng / Vonng (rh@vonng.com)
#==============================================================#


#--------------------------------------------------------------#
# Utils
#--------------------------------------------------------------#
__CN='\033[0m';__CB='\033[0;30m';__CR='\033[0;31m';__CG='\033[0;32m';
__CY='\033[0;33m';__CB='\033[0;34m';__CM='\033[0;35m';__CC='\033[0;36m';__CW='\033[0;37m';
function log_info() {  printf "[${__CG} OK ${__CN}] ${__CG}$*${__CN}\n";   }
function log_warn() {  printf "[${__CY}WARN${__CN}] ${__CY}$*${__CN}\n";   }
function log_error() { printf "[${__CR}FAIL${__CN}] ${__CR}$*${__CN}\n";   }
function log_debug() { printf "[${__CB}HINT${__CN}] ${__CB}$*${__CN}\n"; }
function log_input() { printf "[${__CM} IN ${__CN}] ${__CM}$*\n=> ${__CN}"; }
function log_hint()  { printf "${__CB}$*${__CN}\n"; }
function log_line()  { printf "${__CM}[$*] ===========================================${__CN}\n"; }


#--------------------------------------------------------------#
# Param
#--------------------------------------------------------------#
# check if MIGRATION_CONTEXT is defined as expected
EXPECTED_CONTEXT="{{ src_cls }}.{{ src_db }}"
if [[ "${MIGRATION_CONTEXT}" != "${EXPECTED_CONTEXT}" ]]; then
    log_error "MIGRATION_CONTEXT = ${MIGRATION_CONTEXT} != EXPECTED ${EXPECTED_CONTEXT}"
    log_hint "did you run . activate first?"
    exit 1
fi

log_info   "logical replication progress:   ${SRCCLS}.${SRCDB} : ${DSTCLS}:${DSTDB}"
log_info   "  - SRC URL : ${SRCPG}"
log_info   "  - DST URL : ${DSTPG}"


#--------------------------------------------------------------#
# Execute
#--------------------------------------------------------------#
function relation_progress() {
  local relname=${1}
  local res_src=$(psql "${SRCPG}" -AXtwc "SELECT pg_table_size('${relname}'::RegClass);")
  local res_src_size=$(psql "${SRCPG}" -AXtwc "SELECT pg_size_pretty(pg_table_size('${relname}'::RegClass));")
  local res_dst=$(psql "${DSTPG}" -AXtwc "SELECT pg_table_size('${relname}'::RegClass);")
  local res_dst_size=$(psql "${DSTPG}" -AXtwc "SELECT pg_size_pretty(pg_table_size('${relname}'::RegClass));")
  local res_dst100=$((res_dst * 100))
  percent=0
  if [[ ${res_src} != '0' ]]; then
    percent=$((res_dst100 / res_src))
  fi
  echo "${relname} [${res_dst_size} / ${res_src_size}] : ${percent}%"
}


function overall_progress() {
  tables=$(psql ${DSTPG} -AXtwc "SELECT relname FROM pg_class c JOIN pg_subscription_rel sr ON c.oid = sr.srrelid WHERE relkind = 'r' AND srsubstate != 'r';")
  for table in $tables; do
    relation_progress ${table}
  done
}

overall_progress
